package com.zhufeng.web.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @ClassName: NettyServer
 * @Description TODO
 * @author 月夜烛峰
 * @date 2022/9/23 09:32
 */
@Slf4j
public class NettyServer {

    /**
     * Netty 端口号
     */
    private Integer nettyPort=8880;

    /**
     * 启动方法
     * @throws  Exception
     */
    public void startServer() throws Exception {

        // Netty 线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup wokerGroup = new NioEventLoopGroup();

        try{
            // Netty 启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,wokerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    .option(ChannelOption.SO_BACKLOG,1024 * 1024 * 10)

                    // 设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline pipeline = socketChannel.pipeline();

                            pipeline.addLast("http-codec",new HttpServerCodec());
                            pipeline.addLast("http-chunked",new ChunkedWriteHandler());
                            pipeline.addLast("aggregator",new HttpObjectAggregator(1024*1024*1024));

                            //pipeline.addLast(new WebSocketServerProtocolHandler("/notice",null,true,65535));
                            // 自定义处理器
                            pipeline.addLast(new WebSocketHandle());

                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(nettyPort)).sync();
            if (channelFuture.isSuccess()) {
                log.info("Netty服务端启动成功, 端口号：{}",nettyPort);
            }
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("Netty服务端启动失败，异常信息为: {}",e);
        } finally {
            bossGroup.shutdownGracefully();
            wokerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        try {
            new NettyServer().startServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
